package com.practice.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.practice.gmall.realtime.app.BaseApp;
import com.practice.gmall.realtime.bean.TrafficPageViewBean;
import com.practice.gmall.realtime.common.Constant;
import com.practice.gmall.realtime.util.FlinkSinkUtil;
import com.practice.gmall.realtime.util.MyTimeUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: DwsTrafficVcChArIsNewPageViewWindow02
 * Package: com.practice.gmall.realtime.app.dws
 * Description: dws层的页面访问数据汇总
 * <p>
 * 度量 页面浏览数，浏览总时长，用户访问数，会话数，页面浏览数，
 * 维度 窗口开始时间，窗口结束时间，时间戳
 *
 * @Author lzy.ethan@qq.com
 * @Create 2023-02-18 9:07
 */
public class DwsTrafficVcChArIsNewPageViewWindow02 extends BaseApp {
    public static void main(String[] args) {
        new DwsTrafficVcChArIsNewPageViewWindow02().init(
                4002,
                "DwsTrafficVcChArIsNewPageViewWindow02",
                2,
                Constant.KAFKA_BROKERS,
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. parse steam to POJO(TrafficPageViewBean) stream
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);

        // 2. window aggregate computation (window length 5 seconds)
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = computeBean(beanStream);

        // 3. write to clickhouse
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficPageViewBean> stream) {
        stream.addSink(FlinkSinkUtil.getClickhouseSink(Constant.DWS_TRAFFIC_VC_CH_AR_IS_NEW_PAGE_VIEW_WINDOW, TrafficPageViewBean.class));
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> computeBean(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        return
                beanStream.keyBy(bean -> bean.getVc()+"_"+bean.getCh()+"_"+bean.getAr()+"_"+bean.getIsNew())// todo 根据统计粒度生成一个key
                        .window(TumblingEventTimeWindows.of(Time.of(5, TimeUnit.SECONDS)))
                        .reduce(new ReduceFunction<TrafficPageViewBean>() {
                            @Override
                            public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                                value1.setUvCnt(value1.getUvCnt() + value2.getUvCnt());
                                value1.setPvCnt(value1.getPvCnt() + value2.getPvCnt());
                                value1.setSvCnt(value1.getSvCnt() + value2.getSvCnt());
                                return value1;
                            }
                        }, new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                            @Override
                            public void process(String s, ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>.Context context, Iterable<TrafficPageViewBean> elements, Collector<TrafficPageViewBean> out) throws Exception {

                                long startTs = context.window().getStart();
                                long endTs = context.window().getEnd();

                                TrafficPageViewBean outputBean = elements.iterator().next();
                                outputBean.setStt(MyTimeUtils.formatMillisToDateString(startTs,"yyyy-MM-dd HH:mm:ss"));
                                outputBean.setEdt(MyTimeUtils.formatMillisToDateString(endTs,"yyyy-MM-dd HH:mm:ss"));

                                outputBean.setTs(System.currentTimeMillis());
                                out.collect(outputBean);
                            }
                        });
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {

                    private ValueState<String> firstVisitState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //firstVisitState = null;自定义状态，可以使用Flink的内嵌状态
                        firstVisitState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitState", String.class));
                    }

                    /**
                     * @Description: 根据数据的内容给数据POJO赋值
                     * @param obj 传入的页面浏览JSON数据
                     * @return: com.practice.gmall.realtime.bean.TrafficPageViewBean
                     * @Author: lzy
                     * @Date:2023-02-18 - 11:08
                     */
                    @Override
                    public TrafficPageViewBean map(JSONObject obj) throws Exception {
                        JSONObject common = obj.getJSONObject("common");
                        String vc = common.getString("vc");
                        String ch = common.getString("ch");
                        String ar = common.getString("ar");
                        String isNew = common.getString("is_new");
                        long ts = obj.getLong("ts");

                        // if this line stand for start a new session
                        long svCnt = 0L;
                        String last_page_id = common.getString("last_page_id");
                        if (last_page_id == null) {
                            svCnt = 1L;
                        }


                        JSONObject page = obj.getJSONObject("page");
                        long duringTime = page.getLong("during_time");

                        //set uvCnt
                        String today = MyTimeUtils.formatMillisToDateString(ts,"yyyy-MM-dd HH:mm:ss");
                        long uvCnt = 0L;

                        // todo find out why it works without null point exception
                        if (!today.equals(firstVisitState.value())){
                            firstVisitState.update(today);
                            uvCnt = 1L;
                        }
                       /* else if (!firstVisitState.equals(today)) {
                            uvCnt = 1L;
                        }*/

                        return new TrafficPageViewBean("", "", vc, ch, ar, isNew, uvCnt, svCnt, 1L, duringTime, ts);
                    }
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withIdleness(Duration.ofSeconds(30))
                        .withTimestampAssigner((element, recordTimestamp) -> element.getTs()));


    }
}
